package com.threaddemo3;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableDemo4 {
    public static void main(String[] args) {
        //用法
        //1、创建Callable:可以有返回值 可以抛出异常
        Callable<Double> callable = new Callable<Double>() {
            @Override
            public Double call() throws Exception {
                Thread.sleep(5000);
                System.out.println("后续。。。。。");
                int i = 10 / 0;
                return 1.5;
            }
        };
        //2、放到线程池中 使用线程池配合使用
        ExecutorService es = Executors.newSingleThreadExecutor();

        //3、将Callable 实例提交到线程池中
        Future<Double> future = es.submit(callable);

        //4、可以获得返回值
        try{
            if(future.isDone()){
                System.out.println("已经完成");
            }else{
                System.out.println("未完成");
            }
            future.cancel(true);
            if(future.isCancelled()){
                System.out.println("已关闭");
            }else{
                System.out.println("未关闭");
            }

            Double ret = future.get();//执行get触发线程执 如果线程中有报错 这里会抛出

            System.out.println("ret = " + ret);

        }catch (Exception e){
            System.out.println("抛出异常了 = " + e.getMessage());
        }
        //5、关闭 ExecutorService
        es.shutdown();
    }
}
